package com.puff.web.view;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.exception.BeetlException;
import org.beetl.ext.web.ParameterWrapper;
import org.beetl.ext.web.SessionWrapper;
import org.beetl.ext.web.WebVariable;

public class BeetlRender  {

	private GroupTemplate gt;
	private boolean byteOutput = true;

	public BeetlRender(GroupTemplate gt) {
		this.gt = gt;
	}

	public void render(String key, HttpServletRequest request, HttpServletResponse response, Object... args) throws IOException {
		Writer writer = null;
		OutputStream os = null;
		String ajaxId = null;
		Template template = null;
		boolean isError = false;
		try

		{
			// response.setContentType(contentType);
			int ajaxIdIndex = key.lastIndexOf("#");
			if (ajaxIdIndex != -1) {
				ajaxId = key.substring(ajaxIdIndex + 1);
				key = key.substring(0, ajaxIdIndex);
				template = gt.getAjaxTemplate(key, ajaxId);

			} else {
				template = gt.getTemplate(key);
			}

			Enumeration<String> attrs = request.getAttributeNames();

			while (attrs.hasMoreElements()) {
				String attrName = attrs.nextElement();
				template.binding(attrName, request.getAttribute(attrName));

			}
			WebVariable webVariable = new WebVariable();
			webVariable.setRequest(request);
			webVariable.setResponse(response);
			template.binding(WebVariable.SESSION, new SessionWrapper(request, request.getSession()));

			template.binding(WebVariable.SERVLET, webVariable);
			template.binding(WebVariable.REQUEST, request);
			template.binding("ctxPath", request.getContextPath());
			template.binding("$page", new HashMap<Object, Object>());
			template.binding("parameter", new ParameterWrapper(request));


			if (byteOutput) {
				os = response.getOutputStream();
				template.renderTo(os);
			} else {
				writer = response.getWriter();
				template.renderTo(writer);
			}

		} catch (IOException e) {
			isError = true;
			throw e;
		} catch (BeetlException e) {
			isError = true;
			// response.setStatus(500);
			//
			throw e;
		}

		finally {
			try {

				if (!isError && writer != null)
					writer.flush();
				if (!isError && os != null) {
					os.flush();
				}
			} catch (IOException e) {
				throw e;
			}
		}
	}

}
